package com.eportal.action.background;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.eportal.action.BaseAction;
import com.eportal.domain.PayRedEnvRule;
import com.eportal.domain.PayWallet;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TLock;
import com.eportal.service.PayRedEnvRuleService;
import com.eportal.service.SysmenuService;
import com.eportal.util.DateUtils;
import com.eportal.util.ValidateUtil;
import com.framework.jqgrid.JqGridPager;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 红包
 * @author chencheng
 *
 */
public class RedPacketAction extends BaseAction implements ModelDriven<PayRedEnvRule> {


    private Map<String, Object> result = new HashMap<String, Object>();
    private static String LISTVIEWURL="/admin/redPacket_listView.action";
    @Autowired
    private PayRedEnvRuleService payRedEnvRuleService;
    @Autowired
	private SysmenuService resourceService;

	/**
     * 红包管理
     */
    public String listView() {
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	getRequest().setAttribute("userRole", userRole);
    	StringBuffer sql = new StringBuffer();
    	
    	if (userRole == 1 || userRole == 2) {
    		sql.append("select a1.*,a2.*,a3.*  from "
    				+ "(select nvl(sum(t.amount),0) as agtAmount from pay_wallet t where t.utype='1') a1, "
    				+ "(select nvl(count(t.sid),0) as red from PAY_RED_ENV_RULE t where t.rstatus='0' and t.audit_status='1')  a2, "
    				+ "(select nvl(count(t.sid),0) as redCountTody,nvl(sum(t.amount),0) as redMoneyTody  from PAY_RED_ENV_RECORD t where t.rStatus='2' and to_char(t.ctime,'yyyy-mm-dd')='");
    		sql.append(DateUtils.currentDate());
    		sql.append("') a3");
    		
    	}else if (userRole == 3 || userRole == 4) {
    		String agtCode = user.getAgtCode();
    		sql.append("select a1.*,a2.*,a3.*  from "
        			+ "(select nvl(sum(t.amount),0) as agtAmount from pay_wallet t where t.utype='1' and t.userid='");
    		sql.append(agtCode);
    		sql.append("') a1, "
        			+ "(select nvl(count(t.sid),0) as red from PAY_RED_ENV_RULE t where t.rstatus='0' and t.audit_status='1' and t.agtcode='");
    		sql.append(agtCode);
    		sql.append("')  a2, "
        			+ "(select nvl(count(t.sid),0) as redCountTody,nvl(sum(t.amount),0) as redMoneyTody  from PAY_RED_ENV_RECORD t where t.rStatus='2' and to_char(t.ctime,'yyyy-mm-dd')='");
    		sql.append(DateUtils.currentDate());
    		sql.append("' and t.agtcode='");
    		sql.append(agtCode);
    		sql.append("') a3");
    	}else {
    		return "error";
    	}
    	List<Map<String, Object>>   countAmount  = payRedEnvRuleService.countQuery(sql.toString());
    	getRequest().setAttribute("agtAmount", countAmount.get(0).get("AGTAMOUNT"));
    	getRequest().setAttribute("red", countAmount.get(0).get("RED"));
    	getRequest().setAttribute("redCountTody", countAmount.get(0).get("REDCOUNTTODY"));
    	getRequest().setAttribute("redMoneyTody", countAmount.get(0).get("REDMONEYTODY"));
    	return SUCCESS;
    }
    
    
    /**
     * 分页查询
     */
    public void page() throws Exception {
    	JqGridPager page = new JqGridPager();
        String rName = getRequest().getParameter("rName");
    	String status = getRequest().getParameter("status");
    	
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder(" 1=1 ");
    	
    	if (userRole == 3 || userRole == 4) {
			where.append(" and t.agtCode ='");
			where.append(user.getAgtCode());
			where.append("'");
			
		}else if (userRole == 5 || userRole == 6) {
    		return;
    	}
    	
    	if (!StringUtils.isBlank(rName)) {
    		where.append(" and t.rName like '%");
    		where.append(rName);
    		where.append("%'");
    	}
    	if (!StringUtils.isBlank(status)) {
    		if ("0".equals(status)) {
    			where.append(" and t.audit_status = '0' and and t.rStatus='0'");
			}else if ("1".equals(status)) {
				where.append(" and t.audit_status = '1' and t.rStatus='0'");			
			}else if ("2".equals(status)) {
				where.append(" and t.rStatus='1'");	
			}
    		where.append("'");
    	}
    	page.setWhere(where.toString());
        setPage(getRequest(), page);
        List<Map<String, Object>> buttonMap = resourceService.getButton(LISTVIEWURL);
        StringBuffer sqlappend = new StringBuffer();
        
        for (Map<String, Object> map : buttonMap) {
			if("查看红包报表".equals(map.get("mName"))){
				sqlappend.append(",1a");
			}
			if("红包编辑".equals(map.get("mName"))){
				sqlappend.append(",2b");
			}
			if("红包详情".equals(map.get("mName"))){
				sqlappend.append(",3c");
			}
			if("红包下架".equals(map.get("mName"))){
				sqlappend.append(",5E");
			}
		}
        
         //comunityId存储形式为“,320,381,301,303, ”。先在comunity表中查出来id在其中的组成集合，再在comunity表中查询出名称，再组合
         // 如果in()里面放表中的字符串，是不行的，会报无效的数字，所以用查询集合的方式。
        StringBuffer sql  = new StringBuffer();
		sql.append("select t.sid ,"
				+ "(select a.agtname from t02_agtent a where a.agtcode=t.accept_agtcode) as agtname,"
				+ "(select XMLAGG(XMLELEMENT(E, c.communityname || ',')).EXTRACT('//text()').getclobval() as cname  "
				+ "from t03_community c "
				+ "where c.sid in(select cm.sid from T03_COMMUNITY cm where instr((select pr.accept_communityid from pay_red_env_rule pr where t.sid=pr.sid), ','||cm.sid||',') > 0)"
				+ ") as comuName, "
				+ "t.rname,t.agtcode,t.accept_communityid as communityids,t.cnum,t.send_num as sendNum ,t.amount,nvl(t.send_amount,0) as sendAmount ,to_char(t.date_start,'yyyy-mm-dd') as dateStart,t.date_end,to_char(t.date_end,'yyyy-mm-dd') as dateEnd ,to_char(t.time_start,'HH24:mi') as timeStart ,to_char(t.time_end,'HH24:mi') as timeEnd ,t.rstatus,t.audit_status as auditStatus ");
		if(sqlappend.length() >0){
			sql.append(sqlappend.toString());
		}
		sql.append(" from pay_red_env_rule t ");
		page.setSidx(" t.rstatus, "
				+ "case when t.rstatus='0' then t.audit_status end,"
				+ "case when t.rstatus='0' and t.audit_status='0' then t.ctime  "
				+ " WHEN t.rstatus='0' and t.audit_status='1' then t.atime "
				+ " WHEN t.rstatus='1' then t.offtime  END ");
		page.setSord("desc");
        List<Map<String, Object>> redPacket = payRedEnvRuleService.list(page,sql);
		
        jqGridQueryMap(TLock.class, getRequest(), redPacket, getResponse(), page);
    }

    
//    /**
//     * sql查询拼装
//     * @param userRole 
//     * @param ifNeed 1：需要追加到超管红包，0：不需要追加到超管红包
//     */
//    private String sqlWhere(Sysopt user, int userRole, int ifNeed) {
//    	StringBuilder where = new StringBuilder();
//    	where.append(" 1=1 ");
//    	if(userRole == 1){
//    		where.append("and rName !='平台超级管理员红包' ");
//    	}else{//非平台超级管理员,先查出内部管理红包
//    		where.append("and rAgtent ='");
//    		where.append(user.getAgtCode());
//    		where.append("' ");
//    		where.append("and rCommunity ='");
//    		where.append(user.getCommunityId());
//    		where.append("' ");
//    		where.append("and isAdmin = '0'");
//			where.append(" and sid not in (");
//			where.append(user.getRoles());
//			where.append(")");
//    	}
//    	if(ifNeed == 0){
//    		return where.toString();
//    	}
//    	StringBuilder sb = new StringBuilder("select Sysr.* from (");
//    	sb.append("select * from Sysroles where ");
//    	//加上合作方超级管理员红包
//    	if(userRole == 2){
//    		where.append(" union all select * from Sysroles  where  isAdmin = '1' and rLevel=1 ");
//    	}
//    	if(userRole == 3){//加上社区超管红包
//        	where.append(" union all select * from Sysroles where rAgtent ='");
//        	where.append(user.getAgtCode());
//        	where.append("' ");
//        	where.append("and isAdmin = '1' and rLevel=2 ");
//        }
//    	sb.append(where);
//    	sb.append(") Sysr");
//		return sb.toString();
//	}


    /**
     * 红包修改
     */
    public String editView() {
    	PayRedEnvRule payRedEnvRule = (PayRedEnvRule) payRedEnvRuleService.get(PayRedEnvRule.class,getModel().getSid());
        getRequest().setAttribute("payRedEnvRule", payRedEnvRule);
        return SUCCESS;
    }
    
    /**
     * 红包详情
     */
    public String tetailView() {
    	PayRedEnvRule payRedEnvRule = (PayRedEnvRule) payRedEnvRuleService.get(PayRedEnvRule.class,getModel().getSid());
    	getRequest().setAttribute("payRedEnvRule", payRedEnvRule);
    	return SUCCESS;
    }

    /**
     * 红包修改保存
     * @throws IOException 
     */
    public void update() {
    	Map<String, Object> map = new HashMap<String, Object>();
		String msg = ValidateUtil.validate(payRedEnvRule);
		if (msg.length() == 0) {
			PayRedEnvRule payRedEnvRule = getModel();
			result = new HashMap<String, Object>();
			int cNum = payRedEnvRule.getcNum();
			if (cNum == 0) {
				error("红包总个数不能为空或为零");
				return;
			}
			String rType = payRedEnvRule.getrType();
			if ("0".equals(rType)) {
				BigDecimal avgAmount = payRedEnvRule.getAvgAmount();
				if(avgAmount.compareTo(BigDecimal.ZERO) ==0){
					error("固定红包金额不能为空或为零");
					return;
				}
			}else{
				BigDecimal amount = payRedEnvRule.getAmount();
				if(amount.compareTo(BigDecimal.ZERO) ==0){
					error("红包总金额不能为空或为零");
					return;
				}
				BigDecimal minAmount = payRedEnvRule.getMinAmount();
				if(minAmount.compareTo(BigDecimal.ZERO) ==0){
					error("红包最小金额不能为空或为零");
					return;
				}
				
			}
			String range = payRedEnvRule.getRange();
			if("2".equals(range)){
				if(StringUtils.isBlank(payRedEnvRule.getAcceptCommunityId())){
					error("请选择上架小区");
					return;
    			}
			}
    		String showTime = getRequest().getParameter("showTime");
    		String expiredTime = getRequest().getParameter("expiredTime");
		    result = payRedEnvRuleService.updatePayRedEnvRuleMethod(showTime,expiredTime,payRedEnvRule);
		} else {
			result.put("code", 0);
			result.put("msg", msg);
		}
		responseBody(result);
    }
   

    /**
     * 红包增加
     */
    public String addView() {
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	if (userRole != 3 && userRole != 4) {
    		return "error";
		}
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	getRequest().setAttribute("agt", user.getAgtCode());
    	getRequest().setAttribute("agtmoney", getPayWalletAmount(user.getAgtCode()));
    	
        return SUCCESS;
    }

    /**
     * 红包新增保存
     * @throws IOException 
     */
    public void add() {
    	Map<String, Object> map = new HashMap<String, Object>();
		String msg = ValidateUtil.validate(payRedEnvRule);
		if (msg.length() == 0) {
			PayRedEnvRule payRedEnvRule = getModel();
			result = new HashMap<String, Object>();
			int cNum = payRedEnvRule.getcNum();
			if (cNum == 0) {
				error("红包总个数不能为空或为零");
				return;
			}
			String rType = payRedEnvRule.getrType();
			if ("0".equals(rType)) {
				BigDecimal avgAmount = payRedEnvRule.getAvgAmount();
				if(avgAmount.compareTo(BigDecimal.ZERO) ==0){
					error("固定红包金额不能为空或为零");
					return;
				}
			}else{
				BigDecimal amount = payRedEnvRule.getAmount();
				if(amount.compareTo(BigDecimal.ZERO) ==0){
					error("红包总金额不能为空或为零");
					return;
				}
				BigDecimal minAmount = payRedEnvRule.getMinAmount();
				if(minAmount.compareTo(BigDecimal.ZERO) ==0){
					error("红包最小金额不能为空或为零");
					return;
				}
				
			}
			String range = payRedEnvRule.getRange();
			if("2".equals(range)){
				if(StringUtils.isBlank(payRedEnvRule.getAcceptCommunityId())){
					error("请选择上架小区");
					return;
    			}
			}
    		String showTime = getRequest().getParameter("showTime");
    		String expiredTime = getRequest().getParameter("expiredTime");
		    result = payRedEnvRuleService.addPayRedEnvRuleMethod(showTime,expiredTime,payRedEnvRule);
		} else {
			result.put("code", 0);
			result.put("msg", msg);
		}
		responseBody(result);
    }
    
    /**
     * 上线页面
     */
    public String upView() {
    	String sid  = getRequest().getParameter("sid");
    	PayRedEnvRule payRedEnvRule = (PayRedEnvRule) payRedEnvRuleService.get(PayRedEnvRule.class,Long.parseLong(sid));
        getRequest().setAttribute("payRedEnvRule", payRedEnvRule);
        return SUCCESS;
    }
    
    /**
     * 红包上线
     */
    public void up() {
    	String sid  = getRequest().getParameter("sid");
    	String redId  = getRequest().getParameter("redId");
    	if (StringUtils.isBlank(redId)) {
    		error("金融魔方红包ID不能为空");
    		return;
    	}
    	result = new HashMap<String, Object>();
    	result = payRedEnvRuleService.upMethod(sid,redId);
    	responseBody(result);
    }
    /**
     * 下线
     */
    public void off() {
    	String sid  = getRequest().getParameter("sid");
    	result = new HashMap<String, Object>();
    	result = payRedEnvRuleService.offMethod(sid);
    	responseBody(result);
    }
    private void error(String msg) {
    	result.put("code", 0);
		result.put("msg", msg);
		responseBody(result);
	}


	/**
     * 如何充值页面
     * @return
     */
    public String howRechargeView(){
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	getRequest().setAttribute("userRole", userRole);
    	StringBuffer sql = new StringBuffer();
    	sql.append("select nvl(sum(t.amount),0) as agtAmount from pay_wallet t where t.utype='1'");
    	if (userRole == 1 || userRole == 2) {
    	}else if (userRole == 3 || userRole == 4) {
    		sql.append(" and t.userid='");
    		sql.append(user.getAgtCode());
    		sql.append("'");
    	}else {
    		return "error";
    	}
    	List<Map<String, Object>>   countAmount  = payRedEnvRuleService.countQuery(sql.toString());
    	getRequest().setAttribute("agtAmount", countAmount.get(0).get("AGTAMOUNT"));
    	
    	return SUCCESS;
    }
    
    /**
     * 充值提现记录页面
     * @return
     */
    public String rechargeListView(){
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	getRequest().setAttribute("userRole", userRole);
    	return SUCCESS;
    }
    
    /**
     * 充值提现记录查询
     */
    public void rechargeList() throws Exception {
    	JqGridPager page = new JqGridPager();
        String agtCode = getRequest().getParameter("agtCode");
        String type = getRequest().getParameter("type");
    	String ptime1 = getRequest().getParameter("ptime1");
    	String ptime2 = getRequest().getParameter("ptime2");
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder(" 1=1 ");
    	if (userRole == 1 || userRole == 2 ){
    		if (!StringUtils.isBlank(agtCode)) {
        		where.append(" and  w.userid = '");
        		where.append(agtCode);
        		where.append("'");
        	}
    	}else if (userRole == 3 || userRole == 4 ){
    		where.append(" and  w.userid  = '");
    		where.append(user.getAgtCode());
    		where.append("'");
    	}else if (userRole == 5 || userRole == 6) {
    		return;
    	}
    	
    	if (!StringUtils.isBlank(type)) {
    		where.append(" and t.dtype = '");
    		where.append(type);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(ptime1)) {
    		 where.append(" and t.ctime >= to_date( '");
    		 where.append(ptime1);
    		 where.append(" 00:00:00");
             where.append("' ,'yyyy-mm-dd HH24:mi:ss') ");
    	}
    	if (!StringUtils.isBlank(ptime2)) {
    		 where.append(" and t.ctime <= to_date( '");
             where.append(ptime2);
             where.append(" 23:59:59");
	         where.append("' ,'yyyy-mm-dd HH24:mi:ss') ");
    	}
    	page.setWhere(where.toString());
        setPage(getRequest(), page);
        
        StringBuffer sql  = new StringBuffer();
		sql.append("select t.sid,t.dtype,t.amount,to_char(t.ctime,'yyyy-mm-dd HH24:mi:ss') as ctime,t.comm,a.agtname,s.uname "
				+ "from pay_detail t "
				+ "left join pay_wallet w on t.wallet_id=w.sid and w.uType='1' "
				+ "left join t02_agtent a on w.userid=a.agtcode "
				+ "left join sysopt s on s.sid=t.optid ");
        List<Map<String, Object>> payDetail = payRedEnvRuleService.list(page,sql);
		
        jqGridQueryMap(TLock.class, getRequest(), payDetail, getResponse(), page);
    }
    /**
     * 充值提现
     */
    public void recharge() {
    	result = new HashMap<String, Object>();
    	String type  = getRequest().getParameter("type");
    	String agtCode  = getRequest().getParameter("agtCode");
    	String changeAmount =  getRequest().getParameter("changeAmount");
    	String comm =  getRequest().getParameter("comm");
    	result = payRedEnvRuleService.rechargeMethod(type,agtCode,changeAmount,comm);
    	responseBody(result);
    }
    /**
     * 充值提现
     * @return
     */
    public String rechargeView(){
    	return SUCCESS;
    }
    
    /**
     * 用户余额
     */
    public void getAmount() {
    	result = new HashMap<String, Object>();
    	String agtCode  = getRequest().getParameter("agtCode");
    	String amount = getPayWalletAmount(agtCode);
		result.put("amount", amount);
    	responseBody(result);
    }
    
    /**
     * 查询用户余额
     * @param agtCode
     * @return
     */
    private String getPayWalletAmount(String agtCode) {
		PayWallet payWallet = payRedEnvRuleService.getPayWallet(agtCode);
		if(payWallet == null){
			return "0";
		}else{
			return payWallet.getAmount().toString();
		}
	}


	/**
     * 审核红包
     * @return
     */
    public String auditRedListView(){
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	getRequest().setAttribute("userRole", userRole);
        return SUCCESS;
    }
    
    /**
     * 审核红包分页查询
     */
    public void auditPage() throws Exception {
    	JqGridPager page = new JqGridPager();
        String agtCode = getRequest().getParameter("agtCode");
        String rName = getRequest().getParameter("rName");
    	String status = getRequest().getParameter("status");
    	
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder(" 1=1 ");
    	
    	if (userRole == 3 || userRole == 4 || userRole == 5 || userRole == 6) {
    		return;
    	}
    	if (!StringUtils.isBlank(agtCode)) {
    		where.append(" and t.agtCode = '");
    		where.append(agtCode);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(rName)) {
    		where.append(" and t.rName like '%");
    		where.append(rName);
    		where.append("%'");
    	}
    	if (!StringUtils.isBlank(status)) {
    		if ("1".equals(status)) {
    			where.append(" and t.audit_status = '0");
			}else if ("2".equals(status)) {
				where.append(" and t.audit_status = '1' and t.rStatus='0");			
			}else if ("3".equals(status)) {
				where.append(" and t.rStatus='1");	
			}
    		where.append("'");
    	}
    	
    	page.setWhere(where.toString());
        setPage(getRequest(), page);
        
        List<Map<String, Object>> buttonMap = resourceService.getButton(LISTVIEWURL);
        StringBuffer sqlappend = new StringBuffer();
        
        for (Map<String, Object> map : buttonMap) {
			if("红包详情".equals(map.get("mName"))){
				sqlappend.append(",1a");
			}
			if("红包上线".equals(map.get("mName"))){
				sqlappend.append(",2b");
			}
		}
        
        StringBuffer sql  = new StringBuffer();
		sql.append("select t.sid,t.rname,t.rStatus,t.audit_status as auditStatus,t.cnum,t.send_num as sendNum ,t.amount,nvl(t.send_amount,0) as sendAmount ,to_char(t.ctime,'yyyy-mm-dd HH24:mi:ss') as ctime,agtname,s.uname,to_char(t.atime,'yyyy-mm-dd HH24:mi:ss') as atime ");
		if(sqlappend.length() >0){
			sql.append(sqlappend.toString());
		}
		sql.append(" from pay_red_env_rule t "
				+ "left join t02_agtent a on t.agtcode=a.agtcode "
				+ "left join sysopt s on t.ausername=s.sid ");
//		page.setSidx(" t.rstatus, "
//				+ "case when t.rstatus='0' then t.audit_status end,"
//				+ "case when t.rstatus='0' and t.audit_status='0' then t.ctime  "
//				+ " WHEN t.rstatus='0' and t.audit_status='1' then t.atime "
//				+ " WHEN t.rstatus='1' then t.offtime  END ");
		page.setSidx(" t.rstatus, t.audit_status,t.atime ");
		page.setSord("desc");
        List<Map<String, Object>> redPacket = payRedEnvRuleService.list(page,sql);
		
        jqGridQueryMap(TLock.class, getRequest(), redPacket, getResponse(), page);
    }
    /**
     * 查看报表
     * @return
     */
    public String reports(){
    	String ruleId = getRequest().getParameter("ruleId");
    	String rName = getRequest().getParameter("rName");
    	getRequest().setAttribute("ruleId", ruleId);
    	getRequest().setAttribute("rName", rName);
    	return SUCCESS;
    }
    
    /**
     * 红包发放记录
     * @return
     */
    public String sendRedNotesView(){
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	getRequest().setAttribute("userRole", userRole);
    	return SUCCESS;
    }
    
    /**
     * 红包发放记录查询
     */
    public void sendRedNotes() throws Exception {
    	JqGridPager page = new JqGridPager();
        String agtCode = getRequest().getParameter("agtCode");
        String communityId = getRequest().getParameter("communityId");
        String rName = getRequest().getParameter("rName");
        String cbName = getRequest().getParameter("cbName");
    	String pid = getRequest().getParameter("pid");
    	String tel = getRequest().getParameter("tel");
    	String ptime1 = getRequest().getParameter("ptime1");
    	String ptime2 = getRequest().getParameter("ptime2");
    	String ruleId = getRequest().getParameter("ruleId");
    	
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder(" 1=1 ");
    	
    	if (userRole == 1 || userRole == 2 ){
    		if (!StringUtils.isBlank(agtCode)) {
        		where.append(" and  t.agtcode = '");
        		where.append(agtCode);
        		where.append("'");
        	}
    	}else if (userRole == 3 || userRole == 4 ){
    		where.append(" and  t.agtcode = '");
    		where.append(user.getAgtCode());
    		where.append("'");
    	}else if (userRole == 5 || userRole == 6) {
    		return;
    	}
    	if (!StringUtils.isBlank(communityId)) {
    		where.append(" and t.communityid = '");
    		where.append(communityId);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(ruleId)) {
    		where.append(" and t.rule_id = '");
    		where.append(ruleId);
    		where.append("'");
    	}
    	
    	if (!StringUtils.isBlank(rName)) {
    		where.append(" and p.rName like '%");
    		where.append(rName);
    		where.append("%'");
    	}
    	if (!StringUtils.isBlank(cbName)) {
    		where.append(" and l.install_lock_name like '%");
    		where.append(cbName);
    		where.append("%'");
    	}
    	if (!StringUtils.isBlank(pid)) {
    		where.append(" and k.pid = '%");
    		where.append(pid);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(tel)) {
    		where.append(" and u.tel like '%");
    		where.append(tel);
    		where.append("%'");
    	}
    	if (!StringUtils.isBlank(ptime1)) {
   		 where.append(" and t.ctime >= to_date( '");
   		 where.append(ptime1);
   		 where.append(" 00:00:00");
            where.append("' ,'yyyy-mm-dd HH24:mi:ss') ");
	   	}
	   	if (!StringUtils.isBlank(ptime2)) {
	   		 where.append(" and t.ctime <= to_date( '");
	            where.append(ptime2);
	            where.append(" 23:59:59");
		         where.append("' ,'yyyy-mm-dd HH24:mi:ss') ");
	   	}
    	page.setWhere(where.toString());
        setPage(getRequest(), page);
        
        StringBuffer sql  = new StringBuffer();
		sql.append("select t.sid,to_char(t.ctime,'yyyy-mm-dd HH24:mi:ss') as ctime,t.amount,a.agtname,c.communityname,u.tel,p.rname,k.pid,l.install_lock_name as lockName  "
				+ "from PAY_RED_ENV_RECORD t "
				+ "left join t02_agtent a on t.agtcode=a.agtcode "
				+ "left join t03_community c on t.communityid=c.sid "
				+ "left join t04_users u on t.get_userid=u.userid "
				+ "left join pay_red_env_rule p on t.rule_id=p.sid "
				+ "left join t06_keys k on t.key_id=k.sid "
				+ "left join t05_locks l  on k.pid=l.pid");
        List<Map<String, Object>> redPacket = payRedEnvRuleService.list(page,sql);
		
        jqGridQueryMap(TLock.class, getRequest(), redPacket, getResponse(), page);
    }
    
    private PayRedEnvRule payRedEnvRule = new PayRedEnvRule();

    @Override
    public PayRedEnvRule getModel() {
        return payRedEnvRule;
    }
}
